<template>
  <div class="analytics" id="analytics">
    <!-- 顶部统计卡片 -->
    <div class="dashboard-cards">
      <div class="card">
        <div class="card-header">
          <h3 class="card-title">今日采集量</h3>
        </div>
        <div class="card-value">{{ todayCount }}KB</div>
        <div class="card-subtitle">+18.7% 较昨日</div>
      </div>

      <div class="card">
        <div class="card-header">
          <h3 class="card-title">系统可用率</h3>
        </div>
        <div class="card-value">99.8%</div>
        <div class="card-subtitle">+0.2% vs 上周</div>
      </div>

      <div class="card">
        <div class="card-header">
          <h3 class="card-title">平均响应时间</h3>
        </div>
        <div class="card-value">{{ aveRespTime }}s</div>
        <div class="card-subtitle">-0.3s vs 上周</div>
      </div>

      <div class="card">
        <div class="card-header">
          <h3 class="card-title">错误率</h3>
        </div>
        <div class="card-value">{{ errorPercent }}</div>
        <div class="card-subtitle">-0.02% vs 上周</div>
      </div>
    </div>

    <!-- 服务器每日采集量 -->
    <div class="chart-container">
      <div class="chart-toolbar">
        <div class="chart-title">系统性能趋势分析</div>
        <div class="chart-btns">
          <el-button class="btn active">近7天</el-button>
          <el-button class="btn">近一个月</el-button>
          <el-button class="btn">近三个月</el-button>
        </div>
      </div>
      <div class="chart-canvas" id="lineChartDom"></div>
    </div>

    <!-- 数据来源分布和服务器状态监控 -->
    <div class="chart-dataserver">
      <div class="chart-container__left">
        <div class="chart-canvas" id="pieChartDom"></div>
      </div>
      <!-- 服务器状态监控 -->
      <div class="table-container">
        <div class="bar">
          <div class="title">
            <h3>服务器状态监控</h3>
          </div>
          <div class="options">
            <el-input class="input" v-model="searchInput" placeholder="搜索服务器..." suffix-icon="Search"></el-input>
          </div>
        </div>
        <TableWithPageNoCard :table-data="tableServerStatus" table-title="" :border="false" stripe :has-page="false">
          <el-table-column label="服务器" prop="ip"></el-table-column>
          <el-table-column label="CPU使用率" prop="cpuUsagePercent"></el-table-column>
          <el-table-column label="内存使用率" prop="menUsagePercent"></el-table-column>
          <el-table-column label="磁盘使用率" prop="diskUsagePercent"></el-table-column>
          <el-table-column label="状态" prop="server_status"><template #default="scope">
              <el-tag :type="scope.row.status === '正常'
                ? 'success'
                : scope.row.status === '高负载'
                  ? 'warning'
                  : 'info'
                " size="small" round>
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button type="text" size="small" style="color: #456a9e; font-size: 14px"
                @click="() => handleMonitor(scope.row)">
                监控
              </el-button>

              <el-button type="text" size="small" v-if="scope.row.server_status === '高负载'"
                style="color: #ef4444; font-size: 14px" @click="() => handleWarning(scope.row)">
                告警
              </el-button>
              <el-button type="text" size="small" v-else style="color: #22c55e; font-size: 14px"
                @click="() => handleRestart(scope.row)">
                重启
              </el-button>
            </template>
          </el-table-column>
        </TableWithPageNoCard>
      </div>
    </div>
    <!-- 实时日志监控 -->
    <div class="table-container">
      <div class="bar">
        <div class="title">
          <h3>实时日志监控</h3>
        </div>
        <div class="options">
          <el-select v-model="selectedLogType" placeholder="点击选择任务状态" style="width: 180px">
            <el-option label="全部日志" value="1" />
            <el-option label="错误日志" value="2" />
            <el-option label="警告日志" value="3" />
            <el-option label="信息日志" value="4" />
          </el-select>
          <el-button class="btn" style="background: #456a9e; color: white; border: none" icon="Refresh"
            type="primary">刷新</el-button>
          <el-button class="btn" style="background: #22c55e; color: white; border: none" icon="Upload"
            type="primary">导出</el-button>
        </div>
      </div>
      <TableWithPageNoCard :table-data="tableDataLog" :count="totalLog" @load-page-data="getLogPageList" row-key="id"
        :border="false" stripe :has-page="false">
        <!-- <el-table-column label="级别" prop="level">
          <template #default="scope">
            <el-tag :type="scope.row.level === 'INFO'
              ? 'success'
              : scope.row.level === 'WARN'
                ? 'warning'
                : scope.row.level === 'ERROR'
                  ? 'danger'
                  : 'info'
              " size="small" round>
              {{ scope.row.level }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="服务器" prop="ip"></el-table-column>
        <el-table-column label="耗时(秒)" prop="duration"></el-table-column>
        <el-table-column label="创建时间" prop="createTime">
          <template #default="scope">
            {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="任务" prop="taskName"></el-table-column>
        <el-table-column label="消息" prop="taskMsg"></el-table-column>
        <el-table-column label="状态" prop="taskStatus">
          <template #default="scope">
            <el-tag :type="scope.row.taskStatus === 'succ'
              ? 'success'
              : scope.row.taskStatus === '重试'
                ? 'warning'
                : scope.row.taskStatus === '失败'
                  ? 'danger'
                  : 'info'
              " size="small" round>
              {{ scope.row.taskStatus === 'succ' ? "成功" : "" }}
            </el-tag>
          </template>
        </el-table-column>
      </TableWithPageNoCard>
    </div>
  </div>
</template>
<script setup lang="ts">
import TableWithPageNoCard from '@/components/table/TableWithPageNoCard.vue'
import { nextTick, onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import { getDataSource, getMonitorSummary, getServerStatusList, getTaskLogList } from '@/api/monitor'
import dayjs from 'dayjs'
type EChartsOption = echarts.EChartsOption
const initLineChart = () => {
  var chartDom = document.getElementById('lineChartDom')!
  var myChart = echarts.init(chartDom)
  var option: EChartsOption
  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['数据采集量', '成功率(%)'],
      textStyle: {
        color: '#eee',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },

    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLabel: {
        color: '#ccc',
      },
      axisPointer: {
        type: 'shadow',
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#aaa',
          width: 1,
          type: 'dashed',
        },
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '数据采集量',
        min: 0,
        max: 100000,
        interval: 20000,
        axisLabel: {
          color: '#ccc',
          formatter: '{value} 条',
        },
      },
      {
        type: 'value',
        min: 0,
        max: 100,
        interval: 20,
        name: '成功率(%)',
        axisLabel: {
          color: '#ccc',
        },
      },
    ],
    series: [
      {
        name: '数据采集量',
        type: 'bar',
        itemStyle: {
          color: '#456a9e',
        },
        label: {
          color: '#fff',
        },
        tooltip: {
          valueFormatter: function (value) {
            return value + ' 条'
          },
        },
        data: [12000, 15000, 13500, 17000, 16500, 18000, 19200],
      },
      {
        name: '成功率(%)',
        type: 'line',
        yAxisIndex: 1,
        lineStyle: {
          width: 4,
        },
        itemStyle: {
          color: '#00ff00',
        },

        tooltip: {
          valueFormatter: function (value) {
            return value + '%'
          },
        },
        smooth: true,
        label: {
          color: '#fff',
        },
        data: [92.1, 94.8, 91.3, 95.2, 93.9, 96.5, 95.8],
        symbolSize: 10,
      },
    ],
  }
  option && myChart.setOption(option)
}
const initPieChart = () => {
  var chartDom = document.getElementById('pieChartDom')!
  var myChart = echarts.init(chartDom)
  var option: EChartsOption

  option = {
    title: {
      text: '数据来源分布',
      textStyle: {
        color: '#fff',
      },
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'right',
      textStyle: {
        color: '#eee',
      },
    },
    series: [
      {
        name: '数据来源',
        type: 'pie',
        radius: ['30%', '55%'],
        center: ['40%', '50%'],
        data: dataSourceList.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }
  option && myChart.setOption(option)
}
const searchInput = ref('')

const tableServerStatus = ref<{
  ip: string
  cpuUsagePercent: string
  menUsagePercent: string
  diskUsagePercent: string
  status: string
}[]>([])

const handleMonitor = (row: any) => {
  console.log('监控', row)
}
const handleRestart = (row: any) => {
  console.log('重启', row)
}
const handleWarning = (row: any) => {
  console.log('告警', row)
}
const selectedLogType = ref('1')
const tableDataLog = ref<{
  id: number
  ip: string
  taskName: string
  taskStatus: string
  taskMsg: string
  duration: number
  createTime: number
}[]>([])
// 日志总量
const totalLog = ref(0)
/**
 * 获取分页日志
 * @param pageNo 
 * @param pageSize 
 */
const getLogPageList = async (pageNo: number, pageSize: number) => {
  const res = await getTaskLogList(pageNo, pageSize)
  if (res.code === 0) {
    tableDataLog.value = res.data.list
    totalLog.value = res.data.total
  }
}
/**
 * 获取服务器状态列表
 */
const getSerStatusList = async () => {
  const res = await getServerStatusList()
  if (res.code === 0) {
    tableServerStatus.value = res.data
  }
}
/**
 * 今日采集量
 */
const todayCount = ref(0)
/**
 * 错误率
 */
const errorPercent = ref('')
/**
 * 平均响应时间
 */
const aveRespTime = ref(0)
/**
 * 获取监控统计信息
 */
const getServerSummary = async () => {
  const res = await getMonitorSummary()
  if (res.code === 0) {
    todayCount.value = res.data.todayCount
    errorPercent.value = res.data.errorPercent
    aveRespTime.value = res.data.respTimeAvg
  }
}
const dataSourceList = ref<{ name: string, value: number }[]>([])
/**
 * 数据来源分布
 */
const getDataRange = async () => {
  const res = await getDataSource()
  if (res) {
    dataSourceList.value = res.data.map(item => {
      let nameStr = ''
      switch (item.name) {
        case 'news':
          nameStr = '新闻'
          break;
        case 'social':
          nameStr = '社交'
          break;
        case 'travel':
          nameStr = '旅游'
          break;
        case 'ent':
          nameStr = '娱乐'
          break;
        case 'life':
          nameStr = '生活'
          break;
        case 'video':
          nameStr = '视频'
          break;
        default:
          nameStr = ''
          break;
      }
      return {
        name: nameStr,
        value: item.value
      }
    })
    initPieChart()
  }
}
onMounted(() => {
  nextTick(() => {
    initLineChart()

    getLogPageList(1, 10)
    getSerStatusList()
    getServerSummary()
    getDataRange()

  })
})
</script>
<style lang="scss" scoped>
.analytics {
  .dashboard-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 24px;
    margin-bottom: 32px;

    .card {
      background: #1f2a37;
      border-radius: 12px;
      padding: 12px;
      border: 1px solid #374151;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
      }

      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-left: 20px;

        .card-title {
          font-size: 16px;
          color: rgba(255, 255, 255, 0.9);
          font-weight: 500;
        }
      }

      .card-value {
        font-size: 32px;
        font-weight: bold;
        color: #456a9e;
        margin-bottom: 8px;
      }

      .card-subtitle {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.6);
        padding-bottom: 20px;
      }
    }
  }

  .chart-container {
    padding: 12px;
    background: #1f2a37;
    border-radius: 12px;
    padding: 24px;
    border: 1px solid #374151;
    margin-bottom: 24px;

    .chart-canvas {
      min-height: 400px;
    }

    .chart-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .chart-title {
        font-size: 18px;
        font-weight: 600;
        color: white;
      }

      .chart-btns {
        .btn {
          padding: 8px 16px;
          border-radius: 6px;
          border: none;
          cursor: pointer;
          font-size: 14px;
          font-weight: 500;
          transition: all 0.3s ease;
          text-decoration: none;
          display: inline-flex;
          align-items: center;
          gap: 6px;
        }

        .btn.active {
          background: #456a9e;
          color: white;
        }
      }
    }
  }

  .chart-dataserver {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    padding-bottom: 24px;

    .chart-container__left {
      padding: 12px;
      background: #1f2a37;
      border-radius: 12px;
      padding: 24px;
      border: 1px solid #374151;
      margin-bottom: 0;

      .chart-canvas {
        min-height: 400px;
      }

      .chart-toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .chart-title {
          font-size: 18px;
          font-weight: 600;
          color: white;
        }

        .chart-btns {
          .btn {
            padding: 8px 16px;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
          }

          .btn.active {
            background: #456a9e;
            color: white;
          }
        }
      }
    }

    .table-container {
      padding: 24px;
      background-color: #1f2a37;
      border: 1px solid #374151;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .title {
          h3 {
            font-size: 20px;
            color: #ffffff;
            margin: 0;
            padding: 0;
          }
        }

        .options {
          display: flex;
          gap: 8px;

          .input {
            border: 1px solid #374151;
            border-radius: 6px;
            color: white;
            font-size: 14px;
            width: 200px;
          }

          .btn {
            padding: 8px 16px;
            font-size: 14px;
            border-radius: 6px;
            cursor: pointer;
          }
        }
      }
    }
  }

  .table-container {
    padding: 24px;
    background-color: #1f2a37;
    border: 1px solid #374151;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .title {
        h3 {
          font-size: 20px;
          color: #ffffff;
          margin: 0;
          padding: 0;
        }
      }

      .options {
        display: flex;
        gap: 8px;

        .input {
          border: 1px solid #374151;
          border-radius: 6px;
          color: white;
          font-size: 14px;
          width: 200px;
        }

        .btn {
          padding: 8px 16px;
          font-size: 14px;
          border-radius: 6px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
